package main

import (
	"fmt"
	"github.com/boyane/chartroom/common/message"
	"github.com/boyane/chartroom/server/controllers"
	"github.com/boyane/chartroom/server/utils"
	"io"
	"net"
)

type Processor struct {
	Conn net.Conn
}

func (this *Processor) Process() (err error) {
	for {
		ts := &utils.Transfer{}
		ts.Conn = this.Conn
		mes, err := ts.ReadPkg()
		if err != nil {
			if err == io.EOF {
				fmt.Println("客户端退出,服务器端也退出...")
				return err
			}
			fmt.Println("readPkg err", err)
			return err
		}
		err = this.serverProcessMes(&mes)
		if err != nil {
			fmt.Println("serverProcessMes err =", err)
			return err
		}
	}
}

// 封装一个处理不同消息的分发方法
func (this *Processor) serverProcessMes(mes *message.Message) (err error) {
	switch mes.Type {
	case message.LoginMesType: // 处理登陆逻辑
		user := controllers.User{
			Conn: this.Conn,
		}
		err = user.ServerProcessLogin(mes)
	case message.RegisterMesType: // 处理注册逻辑
		user := controllers.User{
			Conn: this.Conn,
		}
		err = user.ServerProcessRegister(mes)
	case message.SmsGroupEmitMesType: // 处理群发消息逻辑
		sms := controllers.Sms{}
		err = sms.HandleSmsGroupMes(mes)
	}
	return
}
